'use strict';
// 引入获取包的package路径
import { packageDirectorySync } from 'pkg-dir';
import path from 'path';
import fs from 'fs';
import { isObject, formatPath } from "@breeze-cli-dev/utils";
import { getDefaultRegistry, getNpmLatestVersion } from '@breeze-cli-dev/get-npm-info';
import npminstall from 'npminstall';
class Package {
  constructor(options) {
    if (!options) throw new Error('Package类的options参数不能为空！');
    if (!isObject(options)) throw new Error('Package类的options参数必须为对象！');
    // package的目标路径
    this.targetPath = options.targetPath;
    // 存储package路径
    this.storeDir = options.storeDir;
    // package的名称
    this.packageName = options.packageName;
    // package的版本
    this.packageVersion = options.packageVersion;
    // this.packageVersion = '1.0.1';
  }
  get cacheFilePath() {
    return path.resolve(this.storeDir, this.packageName);
  }
  async prepare() {
    if (this.storeDir && !fs.existsSync(this.storeDir)) {
      fs.mkdirSync(this.storeDir, { recursive: true });
    }
    if (this.packageVersion === 'latest') {
      this.packageVersion =  await getNpmLatestVersion(this.packageName);
    }
  }
  async update() {
    // 更新最新版本号
    await this.prepare();
    // 查看本地版本号和线上的最新版本号是否一致
    const  pkgFileObj  = this.getCurrentPackageObj(this.cacheFilePath);
    console.log('this.cacheFilePath', this.cacheFilePath);
    if (pkgFileObj) {
      const { pkgFile } = pkgFileObj;
      if (pkgFile) {
        // 判断是否要去更新
        if (this.packageVersion !== pkgFile.version) {
          await this.install();
        } else {
          console.log('已经是最新版本了');
        }
      } else {
        await this.install();
      }
    } else {
      await this.install();
    }
    
  }
  // 判断package是否存在
  exists() {
    if (this.storeDir) {
      const currentStoreDir = path.resolve(this.storeDir, this.packageName);
      return fs.existsSync(currentStoreDir);
    } else {
      return fs.existsSync(this.targetPath);
    }
  }
  // install 安装package
  async install() {
    await this.prepare();
    return npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: getDefaultRegistry(),
      pkgs: [{
        name: this.packageName,
        version: this.packageVersion,
      }],
    });
  }
  // 获取入口文件路径
  getRootFilePath() {
    // 获取package.json的目录
    let currentDir = this.targetPath;
    if (this.storeDir) {
      currentDir = this.cacheFilePath;
    }
    const { pkgFile, dir } = this.getCurrentPackageObj(currentDir);
    if (pkgFile && pkgFile.main) {
      // 返回入口文件路径
      return formatPath(path.resolve(dir, pkgFile.main));
    }
  }
  // 获取目标package文件参数
  getCurrentPackageObj(currentDir) {
    if (currentDir) {
      const dir = packageDirectorySync({cwd: currentDir})
      if (dir) {
         // 生成package.json的路径并读取package.json文件
        const pkgFile = JSON.parse(fs.readFileSync(path.resolve(dir, 'package.json'), 'utf8'));
        // pkgFile && pkgFile.main
        if (pkgFile) {
          // 返回package.json的内容和package.json的目录
          const pkgObj = {
            pkgFile,
            dir
          }
          return pkgObj
        }
      }
    }
    return null;
  }
}
export default Package;